﻿//
// XN4SL - Xna Framework for Silverlight.
//
using System;
using System.Xml;
using System.IO;
using System.Text;

namespace Xn4Sl.Framework.IO
{
    /// <summary>
    /// StreamReader - replacement fo Security Critical System.IO.StreamReader
    /// </summary>
    public class StreamReader : IDisposable
    {
        /// <summary>
        /// XAP resources reader.
        /// </summary>
        private XmlXapResolver resolver = new XmlXapResolver();

        /// <summary>
        /// Stream for read operations.
        /// </summary>
        private Stream stream = null;

        /// <summary>
        /// Initializes a new instance of the Xn4Sl.Framework.IO.StreamReader 
        /// class for the specified file name.
        /// </summary>
        /// <param name="path">The complete file path to be read.</param>
        public StreamReader(string path)
        {
            try
            {
                this.stream = resolver.GetEntity(new Uri(path, UriKind.Relative), null, null) as Stream;
            }
            catch { }
        }

        /// <summary>
        /// Reads a line of characters from the current stream and returns the data as 
        /// a string.
        /// </summary>
        /// <returns>The next line from the input stream, or null if the end of the input 
        /// stream is reached.</returns>
        public string ReadLine()
        {
            if (this.stream != null)
            {
                StringBuilder line = new StringBuilder();

                while(true)
                {
                    int b = stream.ReadByte();
                    if (b == 0x0D) break;
                    if (b == 0x0A) continue;
                    if (b == -1) break;
                    else line.Append((char)b);
                };
                if(line.Length > 0) return line.ToString();
            }
            return null;
        }

        #region IDisposable Members

        public void Dispose()
        {
            this.stream.Dispose();
        }

        #endregion
    }
}
